package lc;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.IntConsumer;


public class Ex1116 {
   static class ZeroEvenOdd {
        private int n;
        private Semaphore zero, even, odd;
        private volatile int idx;
        public ZeroEvenOdd(int n) {
            this.n = n;
            zero = new Semaphore(1);
            even = odd = new Semaphore(0);
            idx = 0;
        }
    
        // printNumber.accept(x) outputs "x", where x is an integer.
        public void zero(IntConsumer printNumber) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                while ((idx & 1) == 0) {
                    zero.acquire();
                }
                printNumber.accept(0);
                int cur = idx / 2 + 1;
                idx++;
                if ((cur & 1) == 1) {
                    odd.release();
                } else {
                    even.release();
                }
            }
        }
    
        public void even(IntConsumer printNumber) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                while ((idx & 1) == 1) {
                    even.acquire();
                }
                int cur = idx / 2 + 1;
                idx++;
                printNumber.accept(cur);
                zero.release();
            }
        }
    
        public void odd(IntConsumer printNumber) throws InterruptedException {
            for (int i = 0; i < 5; i++) {
                while ((idx & 1) == 1) {
                    odd.acquire();
                }
                int cur = idx / 2 + 1;
                idx++;
                printNumber.accept(cur);
                zero.release();
            }
        }
    }
}
